package org.skyui.beanmanagers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.skyui.jpa.JPAManager;

import com.baycrypt.server.beans.settings.AbstractSettingsBean;

public class SettingsManager {

	static Map<Class<? extends AbstractSettingsBean>, AbstractSettingsBean> beans = new HashMap<Class<? extends AbstractSettingsBean>, AbstractSettingsBean>();

	public static AbstractSettingsBean getBeanForClass(
			Class<? extends AbstractSettingsBean> cl) {

		AbstractSettingsBean bean = beans.get(cl);
		if (bean != null)
			return bean;

		List l = JPAManager.readGlobalBeansFromStorage(cl);

		if (l.size() == 1)
			return (AbstractSettingsBean) l.get(0);

		if (l.size() == 0) {
			try {
				bean = cl.newInstance();
				bean = bean.createDefaultInstance();
				JPAManager.persist(bean);
				beans.put(bean.getClass(), bean);
				return bean;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		throw new Error("Should never happen");

	}

}
